﻿using System;
using System.Buffers;
using System.IO;

namespace WholeSlideImageLibrary
{
    internal class StreamWrapper : IBufferWriter<byte>
    {
        private readonly Stream _stream;
        private byte[]? _buffer;

        private const int MinimumSegmentSize = 16384;

        public StreamWrapper(Stream stream)
        {
            _stream = stream;
        }

        public void Advance(int count)
        {
            if (_buffer is null)
            {
                throw new InvalidOperationException();
            }
            if ((uint)count > (uint)_buffer.Length)
            {
                throw new ArgumentOutOfRangeException(nameof(count));
            }
            _stream.Write(_buffer, 0, count);
            ArrayPool<byte>.Shared.Return(_buffer);
            _buffer = null;
        }

        public Memory<byte> GetMemory(int sizeHint = 0)
        {
            if (!(_buffer is null))
            {
                throw new InvalidOperationException();
            }
            _buffer = ArrayPool<byte>.Shared.Rent(sizeHint);
            return _buffer;
        }

        public Span<byte> GetSpan(int sizeHint = 0)
        {
            if (!(_buffer is null))
            {
                throw new InvalidOperationException();
            }
            _buffer = ArrayPool<byte>.Shared.Rent(Math.Max(MinimumSegmentSize, sizeHint));
            return _buffer;
        }
    }
}
